package com.zjh.document.controller;

import com.zjh.common.entity.Response;
import com.zjh.document.entity.DTO.FileInfo;
import com.zjh.document.service.impl.SFTPFileService;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/documentManager/sftp/files")
public class SFTPFileController {
    @Resource
    private SFTPFileService sftpFileService;

    @GetMapping("/list")
    public Response<List<FileInfo>> listFiles(@RequestParam String path) throws Exception {
        return Response.success(sftpFileService.listFiles(path));
    }

    @GetMapping("/download")
    public ResponseEntity<ByteArrayResource> downloadFile(@RequestParam String filePath) throws Exception {
        byte[] data = sftpFileService.downloadFile(filePath);
        ByteArrayResource resource = new ByteArrayResource(data);

        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(data.length)
                .body(resource);
    }

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> uploadFile(
            @RequestParam String path,
            @RequestParam("file") MultipartFile file) throws Exception {
        sftpFileService.uploadFile(path, file);
        return ResponseEntity.ok("File uploaded successfully");
    }
}